//
//  PhotoSelectorViewController.swift
//  照片选择器
//
//  Created by Tanenbaum on 15/8/7.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit
private let kPhotoSelectorMaxCount = 9
private let PhotoSelectorCellIdentifier = "PhotoSelectorCellIdentifier"

class PhotoSelectorViewController: UICollectionViewController,  PhotoSelectorCellDelegate {

    var currentIndex = 0
    
    lazy var photos = [UIImage]()
    
    init() {
        super.init(collectionViewLayout: UICollectionViewFlowLayout())
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

       
        collectionView?.backgroundColor = UIColor.whiteColor()
        // Register cell classes
        self.collectionView!.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: PhotoSelectorCellIdentifier)
        
        let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)

    }
    
    //MARK: --代理方法
    private func photoSelectorRemovePhoto(cell: PhotoSelectorCell) {
        
        let indexPath = collectionView?.indexPathForCell(cell)
        photos.removeAtIndex(indexPath!.item)
        collectionView?.reloadData()
        
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            return
        }
        currentIndex = indexPath.item
        let picker = UIImagePickerController()
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }


    // MARK: UICollectionViewDataSource

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return (photos.count == kPhotoSelectorMaxCount) ? kPhotoSelectorMaxCount : photos.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoSelectorCellIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
        
        cell.backgroundColor = UIColor.blueColor()
        cell.photoDelegate = self
        cell.image = (indexPath.item < photos.count) ? photos[indexPath.item] : nil
        return cell
    }

}
extension PhotoSelectorViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scale(300)
        if currentIndex > photos.count - 1 {
            
            photos.append(scaleImage)
        }else {
            photos[currentIndex] = scaleImage
        }
        
        print(scaleImage)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

private protocol PhotoSelectorCellDelegate: NSObjectProtocol {
    
    func photoSelectorRemovePhoto(cell:PhotoSelectorCell)
}
private class PhotoSelectorCell: UICollectionViewCell {
    
    var image: UIImage? {
        didSet {
            
            if image == nil {
                
                photoButton.setImage("compose_pic_add")
            }else {
                photoButton.setImage(image, forState: UIControlState.Normal)
            }
            
            removeButton.hidden = (image == nil)
        }
    }
    
    weak var photoDelegate: PhotoSelectorCellDelegate?
    
    @objc func removephoto() {
    
        photoDelegate?.photoSelectorRemovePhoto(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        //添加视图
         addSubview(photoButton)
         addSubview(removeButton)
        
        //设置图片的填充模式
        photoButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        //设置约束
        photoButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let dict = ["photo":photoButton,"remove":removeButton]
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[photo]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[remove]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[remove]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        //添加监听方法
        photoButton.userInteractionEnabled = false
        removeButton.addTarget(self, action: "removephoto", forControlEvents: UIControlEvents.TouchUpInside)
        
        
    }
    
    //懒加载控件
    private lazy var photoButton: UIButton = UIButton(imageName: "compose_pic_add")
    private lazy var removeButton: UIButton = UIButton(imageName: "compose_photo_close")
}
